package com.weiaibenpao.demo.chislim.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.umeng.socialize.Config;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.bean.BaseBean;
import com.weiaibenpao.demo.chislim.bean.Li_UserBeanResult;
import com.weiaibenpao.demo.chislim.bean.UserBean;
import com.weiaibenpao.demo.chislim.hurui.activity.HBaseActivity;
import com.weiaibenpao.demo.chislim.hurui.utils.AppSPUtils;
import com.weiaibenpao.demo.chislim.model.MyModel;
import com.weiaibenpao.demo.chislim.sportoutdoor.presentation.module.PedometerApplication;
import com.weiaibenpao.demo.chislim.ui.marathon.CompleteInfoActivity;
import com.weiaibenpao.demo.chislim.util.ProgressDialog;
import com.weiaibenpao.demo.chislim.util.SharedPrefsUtil;
import com.weiaibenpao.demo.chislim.util.SystemUtil;
import com.weiaibenpao.demo.chislim.util.WriteReadSharedPrefs;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class LoginActivity extends HBaseActivity {


    @BindView(R.id.userNumber)
    EditText userNumber;
    @BindView(R.id.tv_send_key)
    TextView tvSendKey;
    @BindView(R.id.keyPhone)
    EditText keyPhone;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.other_layout)
    RelativeLayout otherLayout;
    @BindView(R.id.tv_user_comment)
    TextView tvUserComment;
    @BindView(R.id.myLogin)
    Button myLogin;

    private String mRegistrationId;



    Context context;
    //-----------------------------------------------------------
    /**
     * 首先获取UMShareAPI
     */
    UMShareAPI mShareAPI;

    SHARE_MEDIA platform;

    UserBean userBean;

    ProgressDialog progressDialog;
    private String state;//是否注册的状态
    private String code;
    private String systemModel;
private String registerSource;
    private long exitTime;
    private boolean isExit=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.e("LoginActivity", "onCreate");
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.ku_bg), 0);
        //获取SharedPreferences对象，第一个参数文件名，第二个参数值
        context = getApplicationContext();

        userBean = UserBean.getUserBean();
        systemModel = SystemUtil.getSystemModel();
        progressDialog = new ProgressDialog(this);
        //如果文件中有用户数据保存，直接进入首页
        if (SharedPrefsUtil.getValue(context, WriteReadSharedPrefs.PREFS_NAME, "content", false)) {
            //if(settings.getBoolean("content",false)){

            Intent intent = new Intent(LoginActivity.this, MainActivity.class);

            startActivity(intent);

            finish();
        }

        //实例化控件
        initView();

        /**
         * 首先获取UMShareAPI
         */
        mShareAPI = UMShareAPI.get(context);


        //微博的回调地址
        Config.REDIRECT_URL = "http://www.chislim.com";

        //第三方登录跳转回登录界面展示动画
//        myImageAnmi = (ImageView) findViewById(R.id.myImageAnmi);
        mRegistrationId = JPushInterface.getRegistrationID(getApplicationContext());
        if (!mRegistrationId.isEmpty()) {
//            Log.e("LoginActivity","registration id is "+mRegistrationId);//在登录接口把这个id传给后台（而非注册接口）
        } else {
            Toast.makeText(this, "Get registration fail, JPush init failed!", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 授权监听
     */
    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onComplete(final SHARE_MEDIA platform, int action, Map<String, String> data) {
            Log.i("授权", "------------------succeed----------------");
            /*初始化UMShareAPI，然后进行用户信息获取：*/
            //获取用户信息,
            /**
             * 新浪微博获取用户信息
             */

            /**
             * QQ   和  微信   获取信息
             */
            mShareAPI.getPlatformInfo(LoginActivity.this, platform, new UMAuthListener() {

                @Override
                public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {


                    switch (platform) {
                        case QQ:
                            userBean.userImage = map.get("profile_image_url");
                            userBean.userName = map.get("screen_name");
                            userBean.userOpenid = map.get("openid");
                            userBean.userSex = map.get("gender");
                            registerSource="QQ";
                            getUserByThree(map.get("openid"), "QQ");
                            break;
                        case SINA:
                            userBean.userImage = map.get("profile_image_url");
                            userBean.userName = map.get("screen_name");
                            userBean.userOpenid = map.get("id");
                            registerSource="weibo";
                            //user.userSex = map.get()
                            getUserByThree(map.get("id"), "weibo");
                            break;
                        case WEIXIN:
                            userBean.userImage = map.get("profile_image_url");
                            userBean.userName = map.get("screen_name");
                            userBean.userOpenid = map.get("openid");
                            registerSource="weixin";
                            getUserByThree(map.get("openid"), "weixin");
                            break;
                    }
                }

                @Override
                public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                    Toast.makeText(LoginActivity.this, i + "------------------获取数据失败----------------", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onCancel(SHARE_MEDIA share_media, int i) {
                    Toast.makeText(LoginActivity.this, i + "------------------获取数据取消----------------", Toast.LENGTH_SHORT).show();
                }
            });
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Log.i("授权", action + "------------------失败----------------");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Log.i("授权", "------------------取消----------------");
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {

            if (mShareAPI != null) mShareAPI.onActivityResult(requestCode, resultCode, data);
            // mShareAPI.onActivityResult(requestCode, resultCode, data);
            Log.i("第三方登录回调", requestCode + " " + resultCode + " " + data.toString() + "=========");

//            myImageAnmi.setBackgroundResource(R.drawable.frame);
            //启动动画
       /* AnimationDrawable anim = (AnimationDrawable) myImageAnmi.getBackground();
        anim.start();*/
            progressDialog.showDialog();
        }
    }

    public void initView() {

    }

    /**
     * 通过电话登录
     */
    public void loginByPhone() {
        String userPhone = userNumber.getText().toString();
        String key_phone = keyPhone.getText().toString().trim();

        if (TextUtils.isEmpty(userPhone)) {
            Toast.makeText(context, "请输入手机号码", Toast.LENGTH_SHORT).show();
            return;

        }
        if (TextUtils.isEmpty(key_phone)) {
            Toast.makeText(context, "请输入验证码", Toast.LENGTH_SHORT).show();
            return;
        }
        progressDialog.showDialog();

        if (myLogin.getText().equals("绑定")){
            getBindLogin(userPhone,key_phone);
        }else if (myLogin.getText().equals("登录")){
            getUserByPhone(userPhone,key_phone);
        }
    }

    private void getBindLogin(String userPhone,String verificationCode) {
        MyModel.getModel().getService().getBindPhone(userBean.userImage,userBean.userName,userBean.userOpenid,registerSource,userPhone,verificationCode).enqueue(new Callback<Li_UserBeanResult>() {
            @Override
            public void onResponse(Call<Li_UserBeanResult> call, Response<Li_UserBeanResult> response) {
                if (response.body()!=null){
                    if (response.body().getCode()==0){
                        WriteReadSharedPrefs.writeUser(context, response.body().getData());
                        WriteReadSharedPrefs.readUser(context, userBean);
                        AppSPUtils.put(LoginActivity.this, "name", response.body().getData().getUserName());
                        AppSPUtils.put(LoginActivity.this, "logoUrl", response.body().getData().getId());
                          startActivity(new Intent(context,CompleteInfoActivity.class));
                        finish();
                    }else {
                        Toast.makeText(context, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<Li_UserBeanResult> call, Throwable throwable) {

            }
        });
        if (progressDialog != null)
            progressDialog.cancelDialog();//added by zjl for fixing bug of window leaked
    }

    /**
     * QQ登录
     *
     * @param v
     */
    public void loginByQq(View v) {
        /*获取客户端安装信息*/
        boolean qqBoolean = mShareAPI.isInstall(this, SHARE_MEDIA.QQ);
        /*选取需要授权的平台，并进行授权，其中umAuthLisrener是回调监听器*/
        if (qqBoolean) {
            platform = SHARE_MEDIA.QQ;
            mShareAPI.doOauthVerify(this, platform, umAuthListener);
        } else {
            Toast.makeText(context, "请安装QQ客户端", Toast.LENGTH_SHORT).show();

        }
    }

    /**
     * 微博登录
     *
     * @param v
     */
    public void loginByWbo(View v) {
        /*获取客户端安装信息*/
        boolean wbBoolean = mShareAPI.isInstall(this, SHARE_MEDIA.SINA);
        /*选取需要授权的平台，并进行授权，其中umAuthLisrener是回调监听器*/
        if (wbBoolean) {
            platform = SHARE_MEDIA.SINA;
            mShareAPI.doOauthVerify(this, platform, umAuthListener);
        } else {
            Toast.makeText(context, "请安装微博客户端", Toast.LENGTH_SHORT).show();

        }
    }

    /**
     * 微信登陆
     *
     * @param v
     */
    public void loginByWxin(View v) {
        //判断是否安装了客户端
        boolean wxBoolean = mShareAPI.isInstall(this, SHARE_MEDIA.WEIXIN);
        /*选取需要授权的平台，并进行授权，其中umAuthLisrener是回调监听器*/
        if (wxBoolean) {
            platform = SHARE_MEDIA.WEIXIN;
            mShareAPI.doOauthVerify(this, platform, umAuthListener);}
//        } else {
//            Toast.makeText(context, "请安装微信客户端", Toast.LENGTH_SHORT).show();
//
//        }
    }

    /**
     * 通过电话号码查询服务器端
     */
    public void getUserByPhone(final String userPhone,String code) {

        Call<Li_UserBeanResult> call = MyModel.getModel().getService().getLoginByPhone(userPhone, code, mRegistrationId, systemModel);

        call.enqueue(new Callback<Li_UserBeanResult>() {
            @Override
            public void onResponse(Call<Li_UserBeanResult> call, Response<Li_UserBeanResult> response) {
                Log.e("LYF", "onResponse: " + new Gson().toJson(response.body()));

                if (response.body() != null) {
                    final Li_UserBeanResult result = response.body();
                    if (result.getCode() == 0) {
                        WriteReadSharedPrefs.writeUser(context, result.getData());
                        WriteReadSharedPrefs.readUser(context, userBean);
                        AppSPUtils.put(LoginActivity.this, "name", result.getData().getUserName());
                        AppSPUtils.put(LoginActivity.this, "logoUrl", result.getData().getId());
                        if (result.getData().getRegister().equals("1")){
                            goToMain();
                       }else {
                            startActivity(new Intent(LoginActivity.this, CompleteInfoActivity.class));
                       }
                    } else {
                        Toast.makeText(context, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<Li_UserBeanResult> call, Throwable t) {

                Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
            }
        });
        if (progressDialog != null)
            progressDialog.cancelDialog();//added by zjl for fixing bug of window leaked
    }

    /**
     * 通过第三方登录
     */
    public void getUserByThree(final String openId, String sourse) {

        Call<Li_UserBeanResult> call = MyModel.getModel().getService().getLoginByThree(openId, sourse, mRegistrationId, systemModel);

        call.enqueue(new Callback<Li_UserBeanResult>() {
            @Override
            public void onResponse(Call<Li_UserBeanResult> call, Response<Li_UserBeanResult> response) {
                if (response.isSuccessful()) {

                    final Li_UserBeanResult result = response.body();
                    AppSPUtils.put(LoginActivity.this, "name", UserBean.getUserBean().userName);
                    AppSPUtils.put(LoginActivity.this, "logoUrl", UserBean.getUserBean().userImage);
                    if (result.getCode() == 0) {
                        Log.e("wlx", "qq: " + new Gson().toJson(response));
                        if (result.getData().getRegister().equals("0")) {
                            otherLayout.setVisibility(View.GONE);
                            tvContent.setVisibility(View.VISIBLE);
                            tvContent.setText("绑定手机号，活动、赛事信息通知更准确及时");
                            myLogin.setText("绑定");

                        } else if (result.getData().getRegister().equals("1")) {
                            //写数据
                            WriteReadSharedPrefs.writeUser(context, result.getData());
                            //读到单例中
                            WriteReadSharedPrefs.readUser(context, userBean);
                            goToMain();
                        }
                    } else {
                        Toast.makeText(LoginActivity.this, "登录失败1", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<Li_UserBeanResult> call, Throwable t) {

                Toast.makeText(LoginActivity.this, "登录失败2", Toast.LENGTH_SHORT).show();
            }
        });
        if (progressDialog != null)
            progressDialog.cancelDialog();//added by zjl for fixing bug of window leaked
    }

    public void goToMain() {
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
//        startActivity(new Intent(LoginActivity.this, CompleteInfoActivity.class));
//        finish();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isExit){
            System.exit(0);
        }
//        if(progressDialog != null ){
//            progressDialog.cancelDialog();
//            progressDialog = null ;
//        }
    }

    @OnClick({R.id.tv_send_key, R.id.myLogin})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_send_key:
                getKey();
                break;
            case R.id.myLogin:
                loginByPhone();
                break;
        }
    }

    private void getKey() {
        String et_phone = userNumber.getText().toString();
        if (TextUtils.isEmpty(et_phone)) {
            Toast.makeText(context, "请输入手机号码", Toast.LENGTH_SHORT).show();
            return;
        }


        sendSms(et_phone);
        changeTime();
        tvSendKey.setClickable(false);
    }

    private void sendSms(String et_phone) {
        MyModel.getModel().getService().getSms(et_phone).enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                Log.e("wlx33", "onResponse: " + new Gson().toJson(response.body()));
                BaseBean baseBean = response.body();
                if (baseBean != null) {
                    if (baseBean.getCode() == 0) {
//                        code=baseBean.getData().getCode();

                    } else {
                        Toast.makeText(context, baseBean.getMsg(), Toast.LENGTH_SHORT).show();

                    }
                } else {

                    Toast.makeText(context, "短信发送失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable throwable) {

            }
        });
    }


    //六十秒倒计时
    public void changeTime() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 60; i >= 0; i--) {
                    try {
                        Message msg = Message.obtain();

                        msg.arg1 = i;
                        handler.sendMessage(msg);
                        Thread.sleep(1000);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int i = msg.arg1;
            tvSendKey.setText("已发送" + i + "s");
            if (i == 0) {
                tvSendKey.setText("重新发送");
                tvSendKey.setClickable(true);
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            exit(keyCode,event);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK &&
                event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次返回键退出程序",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
                isExit=false;
            } else {
                //做一些最后的清理工作
                isExit=true;
                PedometerApplication.destoryActivity();
                finish();

            }
        }
    }



}
